<template>
  <basic-modal v-bind="$attrs" @confirm="handleConfirm">
    <n-space vertical>
      <template v-for="attribute in attributes" :key="attribute.id">
        <div class="select-title">
          <span>{{ attribute.name }}</span>
        </div>
        <n-grid x-gap="10" y-gap="10" :col="24">
          <n-gi
            span="6"
            v-for="attributeValue in attribute.values"
            :key="attributeValue.id"
          >
            <div
              class="custom-choose-item custom-choose-item--small flex items-center justify-center"
              :class="{
                'custom-choose-item--active': isSelected(
                  attribute.id,
                  attributeValue.id
                ),
              }"
              @click.stop="
                handleSelectAttribute(attribute.id, attributeValue.id)
              "
            >
              <div class="title">
                <span> {{ attributeValue.name }} </span>
              </div>
            </div>
          </n-gi>
        </n-grid>
      </template>
    </n-space>
  </basic-modal>
</template>
<script lang="ts" setup>
import { useAttrs, watch, ref } from "vue";
import { useMessage } from "naive-ui";
import { get, debounce } from "lodash-es";
import { getAttributeByProductId } from "@/api/product/productAttribute.api";
import { getTradeinVariant } from "@/api/product/product.api";
import { IChooseVariantProps } from "./props";
import { Attribute } from "@/types/model/product/vos/attributes.vo";

const emit = defineEmits(["confirm"]);

const message = useMessage();
const $attrs = useAttrs();
const props = withDefaults(defineProps<IChooseVariantProps>(), {
  productId: "",
});

const initLoading = ref<boolean>(false);
const attributes = ref<Attribute[]>([]);
const selectedAttribute = ref<Recordable>({});

watch([() => props.productId, () => $attrs.show], ([newVal1, newVal2]) => {
  if (newVal1 && newVal2) {
    getAttributes(newVal1);
  }
});

const getAttributes = async (productId: string) => {
  initLoading.value = true;
  try {
    const res = await getAttributeByProductId(productId);
    const _attributes = get(res, "result") || [];
    let _selectedVaribute: any = {};
    if (_attributes.length) {
      _attributes.forEach((attribute) => {
        _selectedVaribute[attribute.id] = "";
      });
    }
    selectedAttribute.value = _selectedVaribute;
    attributes.value = _attributes;
    console.log(selectedAttribute.value);
  } finally {
    initLoading.value = false;
  }
};

const isSelected = (attributeId: string, attributeValueId: string) => {
  return selectedAttribute.value[attributeId] === attributeValueId;
};

const handleSelectAttribute = debounce(function (
  attributeId: string,
  attributeValueId: string
) {
  if (selectedAttribute.value.hasOwnProperty(attributeId)) {
    selectedAttribute.value[attributeId] = attributeValueId;
  }
},
200);

const handleConfirm = () => {
  const isFull = checkAttributeSelectedFull();
  if (isFull) {
    // 选中所有属性
    handleGetTradeInVariant();
  } else {
    message.error("请选择全部属性");
  }
};

const checkAttributeSelectedFull = () => {
  let flag = true;
  for (const attrId in selectedAttribute.value) {
    if (!selectedAttribute.value[attrId]) {
      flag = false;
      break;
    }
  }
  return flag;
};

const handleGetTradeInVariant = async () => {
  let _attributes = [];
  for (const attrId in selectedAttribute.value) {
    const attrValueId = selectedAttribute.value[attrId];
    if (attrValueId) {
      _attributes.push({
        attrId: attrId,
        attrValueId: attrValueId,
      });
    }
  }
  const params = {
    productId: props.productId,
    attributes: _attributes,
  };

  const res = await getTradeinVariant(params);
  console.log(res);
  const variant = get(res, "result") || {};
  emit("confirm", variant);
};
</script>
